<template>
  <div class="article-list">
    <van-pull-refresh
        v-model="refreshLoading"
        success-text="刷新成功"
        @refresh="onRefresh"
    >
      <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          :error.sync="error"
          error-text="请求失败，点击重新加载"
      >
        <ArticleItem v-for="item in list" :key="item.art_id" :article="item"/>
      </van-list>

    </van-pull-refresh>
  </div>
</template>

<script>
import { fetchArticleList } from '@/api/article'
import ArticleItem from '@/components/article-item'

export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false,
      refreshLoading: false
    }
  },
  computed: {},
  watch: {},
  created () {
  },
  mounted () {
    console.log(this.channel)
  },
  methods: {
    async onRefresh () {
      try {
        const { data } = await fetchArticleList({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })

        const { results } = data.data
        // results里面的数据添加到list
        this.list.unshift(...results)
        //   关闭loading效果
        this.refreshLoading = false
      } catch (e) {
        this.refreshLoading = false
        this.$toast('刷新失败')
      }
    },
    // onload方法List组件会自己调用，
    async onLoad () {
      // 异步更新数据
      try {
        const { data } = await fetchArticleList({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })

        // results里面的数据添加到list
        this.list.push(...data.data.results)
        // loding结束
        this.loading = false

        // finished什么时候为true
        // 记录时间戳
        if (data.data.results.length) {
          //  可以继续请求数据
          this.timestamp = data.data.pre_timestamp
        } else {
          //  不用请求了
          this.finished = true
        }
      } catch (e) {
        // 界面上显示错误
        // 当用户点击了错误提示的时候，会重新触发load事件
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow: auto;
}

</style>
